using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using AvaloniaApplication1.Component.ViewModel;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Service;
using AvaloniaApplication1.Util;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Modbus.Device;
using SukiUI.Dialogs;
using SukiUI.Toasts;

namespace AvaloniaApplication1.ViewModels.ModbusCardViewModel;

public partial class AddModbusDeviceViewModel : ObservableObject
{
    /// <summary>
    /// Modbus设备名称
    /// </summary>
    [ObservableProperty] private string? _modbusDeviceName = "设备1";

    /// <summary>
    /// InfoBar开关
    /// </summary>
    [ObservableProperty] private bool _isOpen;

    /// <summary>
    /// 当前步骤索引
    /// </summary>
    [ObservableProperty] private int _stepIndex = 0;

    [ObservableProperty] private bool _step1Display = true;
    [ObservableProperty] private bool _step2Display = false;
    [ObservableProperty] private bool _step2RtuOverTcpDisplay = false;
    [ObservableProperty] private bool _step2RtuDisplay = false;
    [ObservableProperty] private bool _step3Display = false;


    [ObservableProperty] private List<string>? _connectionTypeList;

    /// <summary>
    /// 连接类型
    /// </summary>
    [ObservableProperty] private string? _selectedConnectionType="RtuOverTcp";

    [ObservableProperty] private ModbusConfig? _modbusConfigs;

    [ObservableProperty] private ModbusTcpConfig? _modbusTcpConfig;

    /// <summary>
    /// 网关名称
    /// </summary>
    [ObservableProperty] private string? _tcpName = "网关1";

    /// <summary>
    /// TCP服务器地址
    /// </summary>
    [ObservableProperty] private string? _tcpServer = "192.168.3.221";

    /// <summary>
    /// TCP端口
    /// </summary>
    [ObservableProperty] private int _tcpPort = 8899;

    /// <summary>
    /// TCP超时时间
    /// </summary>
    [ObservableProperty] private int _tcpTimeout = 3000;
    
    /// <summary>
    /// 从站的数据点轮询时间
    /// </summary>
    [ObservableProperty] private int _intervalTime = 3000;

    [ObservableProperty] private ModbusSerialConfig? _modbusSerialConfig;

    [ObservableProperty] private string _serialName = string.Empty;
    [ObservableProperty] private int _baudRate = 9600;
    [ObservableProperty] private Parity _parity = Parity.None;
    [ObservableProperty] private StopBits _stopBits= StopBits.One;
    [ObservableProperty] private int _dataBits;
    [ObservableProperty] private int _readTimeOut = 3000;
    [ObservableProperty] private int _writeTimeOut = 3000;
    
    
 
    

    [ObservableProperty] private string? _successInfo = null;

    [ObservableProperty] private IModbusManager _modbusManager;
    
    private ISukiDialogManager DialogManager { get; set; }


    public IEnumerable<string> Steps { get; } =
        ["设备配置", "连接配置", "配置完成"];

    // 引用 InfoBar 组件的 ViewModel
    [ObservableProperty] private InfoViewModel _inforBar;

    public AddModbusDeviceViewModel(ModbusConfig modbusConfig, IModbusManager modbusManager,ISukiDialogManager dialogManager)
    {
        DialogManager=dialogManager;
        InforBar = new InfoViewModel();
        ModbusManager = modbusManager;
        ModbusConfigs = modbusConfig;

        StepIndex = 0;
        Step1Display = true;
        Step2Display = false;
        Step3Display = false;
        // 初始化连接类型列表
        ConnectionTypeList = Enum.GetNames(typeof(ModbusConnectionType)).ToList();


        // 设置默认值
        // SelectedConnectionType = ConnectionTypeList.FirstOrDefault()??"null";
    }

    [RelayCommand]
    public void AddDevice()
    {
        // IsOpen = true;
        // IsOpen=false;
        // Severity = "success";
        // Message = InfoDictionary[Severity];
        // // Message = InfoDictionary["Name"] + " added successfully";
        //InforBar.ShowInfo("success add modbus device", "success", "Info", 8000);
    }

    [RelayCommand]
    public async void NextStep()
    {
        if (StepIndex == 0)
        {
            if (SelectedConnectionType == null || ModbusDeviceName == null)
            {
                InforBar.ShowInfo("请完善设备名称和Modbus连接方式", "Warning", "Info", 5000);
                return;
            }

            StepIndex++;
            return;
        }

        if (StepIndex == 1)
        {
            if (!string.IsNullOrWhiteSpace(TcpName) && !string.IsNullOrWhiteSpace(TcpServer) &&
                SelectedConnectionType != null)
            {
                //创捷连接类型配置
                var connectionType = SelectedConnectionType switch
                {
                    "Rtu" => ModbusConnectionType.Rtu,
                    "RtuOverTcp" => ModbusConnectionType.RtuOverTcp,
                    _ => throw new ArgumentOutOfRangeException()
                };
                if (!string.IsNullOrWhiteSpace(ModbusDeviceName)&& connectionType==ModbusConnectionType.RtuOverTcp)
                {
                    ModbusConfigs = new ModbusConfig(
                        ModbusDeviceName, DateTime.Now, connectionType,
                        new SlaveInfo
                        {
                            IntervalTime = IntervalTime
                        },
                        null,
                        false,
                        ModbusManager,
                        DialogManager
                    )
                    {
                        TcpConfig = new ModbusTcpConfig //TCP配置对象初始化
                        {
                            TcpName = TcpName,
                            Server = TcpServer,
                            Ports = new Dictionary<string, int>
                            {
                                { TcpName, TcpPort }
                            },
                            Timeout = TcpTimeout
                        },
                    };
                    var result = await ModbusManager.AddModbusDeviceAsync(ModbusConfigs);
                    
                    if (result)
                    {
                        StepIndex++;
                        return;
                    }

                    InforBar.ShowInfo("添加设备失败", "Error", "Error", 5000);
                    return;
                }
                if (!string.IsNullOrWhiteSpace(ModbusDeviceName)&& connectionType==ModbusConnectionType.Rtu)
                {
                    ModbusConfigs = new ModbusConfig(
                        ModbusDeviceName, DateTime.Now, connectionType,
                        new SlaveInfo(),
                        null,
                        false,
                        ModbusManager,
                        DialogManager
                    )
                    {
                        SerialConfig = new ModbusSerialConfig //串口配置对象初始化
                        {
                            SerialName = TcpName,
                            BaudRate = BaudRate,
                            DataBits = 8,
                            StopBits = StopBits.One,
                            Paritys = Parity.None,
                            ReadTimeout = ReadTimeOut,
                            WriteTimeout = WriteTimeOut
                            
                        }
                    };
                    var result = await ModbusManager.AddModbusDeviceAsync(ModbusConfigs);
                    // try
                    // {
                    //     // 使用 SqlSugar 进行数据库操作
                    //     var dbresult = await DataBaseManager.Db.Insertable(ModbusConfigs).ExecuteCommandAsync();
                    //
                    //     if (dbresult > 0)
                    //     {
                    //         InforBar.ShowInfo("设备配置MySql保存成功", "Success", "提示", 5000);
                    //     }
                    // }
                    // catch (Exception ex)
                    // {
                    //     InforBar.ShowInfo($"保存失败: {ex.Message}", "Error", "错误", 5000);
                    // }
                    if (result)
                    {
                        StepIndex++;
                        return;
                    }
                    InforBar.ShowInfo("添加设备失败", "Error", "Error", 5000);
                }

                InforBar.ShowInfo("请完善设备名称", "Warning", "提示", 5000);
                return;

                // {
                //     DeviceName = ModbusDeviceName, // 设备名称
                //     ConnectionType = connectionType, // 设置连接类型为RTU-TCP
                //     TcpConfig = new ModbusTcpConfig //TCP配置对象初始化
                //     {
                //         TcpName = TcpName,
                //         Server = TcpServer,
                //         Ports = new Dictionary<string, int>
                //         {
                //             { TcpName, TcpPort }
                //         },
                //         Timeout = TcpTimeout
                //     },
                //     SerialConfig = new ModbusSerialConfig(), //串口配置对象初始化
                //     CreatedTime = DateTime.Now,
                //     SlaveConfig = new ModbusSlaveConfig() //从站配置对象初始化
                // };
            }

            InforBar.ShowInfo("请完善TCP连接参数", "Warning", "提示", 5000);
            return;
        }

        if (StepIndex == 2)
        {
            StepIndex = 0;
            ModbusDeviceName = null;
            SelectedConnectionType = null;
        }
    }

    partial void OnSelectedConnectionTypeChanged(string value)
    {
    }

    /// <summary>
    /// 步骤索引改变时，更新主步骤显示
    /// </summary>
    /// <param name="value">步骤索引</param>
    partial void OnStepIndexChanged(int value)
    {
        // 更新主步骤显示
        Step1Display = value == 0;
        Step2Display = value == 1;
        Step3Display = value == 2;
        // 更新第2步的子步骤显示（仅当在第2步时）
        if (value == 1 && !string.IsNullOrEmpty(SelectedConnectionType))
        {
            Step2RtuOverTcpDisplay = SelectedConnectionType == "RtuOverTcp";
            Step2RtuDisplay = SelectedConnectionType == "Rtu";
        }
        else
        {
            Step2RtuOverTcpDisplay = false;
            Step2RtuDisplay = false;
        }

        if (value == 2)
        {
            SuccessInfo = $"设备“{ModbusDeviceName}”添加成功,连接类型为-{SelectedConnectionType}";
        }
    }

    [RelayCommand]
    public void PreviousStep()
    {
        StepIndex--;

        if (StepIndex == 0)
        {
            //清空主题列表和SelectedDeviceId
        }

        if (StepIndex == 1)
        {
            SelectedConnectionType = null;
            ModbusDeviceName = null;
        }

        if (StepIndex == 2)
        {
        }
    }
}